/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package com.thingsgrid.notice.service.impl;

import com.alibaba.fastjson.JSON;
import com.thingsgrid.notice.entity.NoticeEntiy;
import com.thingsgrid.notice.entity.SendEntiy;
import com.thingsgrid.notice.exception.NoticeException;
import com.thingsgrid.notice.repository.ICommonRepository;
import com.thingsgrid.notice.repository.INoticeRepository;
import com.thingsgrid.notice.service.INoticeService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.SecureUtil;
import org.springblade.core.tool.api.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

/**
 * 服务实现类
 *
 * @author Chill
 */
@Slf4j
@AllArgsConstructor
@Service
public class NoticeServiceImpl  implements INoticeService<NoticeEntiy> {

	@Autowired
	private MongoTemplate mongoTemplate;

    @Autowired
    private INoticeRepository iNoticeRepository;
    @Autowired
    private ICommonRepository iCommonRepository;
    @Override
    public R findOneById(String msgId) {
        try{
            return R.data(iNoticeRepository.findById(msgId).get());
        }catch (Exception e){
            throw new NoticeException(R.fail("根据ID查询失败"));
        }
    }

    @Override
    public List<NoticeEntiy> findOneByIds(List<String> ids) {
        return null;
    }

    @Override
    public NoticeEntiy save(NoticeEntiy noticeEntiy) {
       return  iNoticeRepository.save(noticeEntiy);
    }

    @Override
    public NoticeEntiy update(NoticeEntiy noticeEntiy) {
        return null;
    }

    @Override
    public Page<NoticeEntiy> page(NoticeEntiy noticeEntiy, Pageable page) {
        try{
            BladeUser bladeUser = SecureUtil.getUser();
            List<String> list = Arrays.asList(bladeUser.getAccount());
            List<SendEntiy> listSendEntitys = iCommonRepository.queryByName(new SendEntiy(),"receiver_name",bladeUser.getAccount());
            List<String> listId = new ArrayList<>();
            listSendEntitys.forEach(v->listId.add(v.getMessageTextId()));
			return getNewPage(noticeEntiy,page,listId,bladeUser.getAccount());
        }catch (Exception e){
            throw new NoticeException(R.fail("分页查询失败"));
        }
    }

	/**
	 * 重写的过滤查询 Trans
	 * @param noticeEntiy
	 * @param page
	 * @param list
	 * @return
	 */
    private Page<NoticeEntiy> getNewPage(NoticeEntiy noticeEntiy, Pageable page,List list,String owner){
		Query query = new Query();
		Criteria criteria = new Criteria();
		Criteria criteria1 = new Criteria();

		if(StringUtils.isNoneBlank(noticeEntiy.getMessageType())){
		}
		if(StringUtils.isNoneBlank(noticeEntiy.getTitle())){
			Pattern pattern = Pattern.compile("^.*" + noticeEntiy.getTitle() + ".*$", Pattern.CASE_INSENSITIVE);
			query.addCriteria(criteria.where("title").regex(pattern));
		}
		if(StringUtils.isNoneBlank(noticeEntiy.getContent())){
			Pattern pattern = Pattern.compile("^.*" + noticeEntiy.getContent() + ".*$", Pattern.CASE_INSENSITIVE);
			query.addCriteria(criteria.where("content").regex(pattern));
		}
		Criteria creator_name = criteria.where("creator_name").is(owner);

		query.addCriteria(new Criteria().orOperator(Criteria.where("id").in(list),creator_name));
		long count = mongoTemplate.count(query.with(page), NoticeEntiy.class);
		List<NoticeEntiy> noticeEntiys = mongoTemplate.find(query, NoticeEntiy.class);
		PageImpl<NoticeEntiy> noticeEntiys1 = new PageImpl<>(noticeEntiys, page, count);
		return  noticeEntiys1;
	}


	@Override
    @Transactional(rollbackFor=Exception.class)
    public R deleteByIds(String ids) {
        try{
            List<String> listId = JSON.parseArray(ids,String.class);
            iCommonRepository.batchDeleteByName(NoticeEntiy.class,listId,"_id");
            iCommonRepository.batchDeleteByName(SendEntiy.class,listId,"message_text_id");
            return R.success("OK");
        }catch (Exception e){
            throw new NoticeException(R.fail("根据ID删除失败"));
        }
    }

    @Override
    public R deleteAll() {
        try{
            iNoticeRepository.deleteAll();
            return R.success("OK");
        }catch (Exception e){
            throw new NoticeException(R.fail("全部删除失败"));
        }
    }

    @Override
    public List<NoticeEntiy> findNoticeByName(String findName, List<String> findVal) {
        return iCommonRepository.queryByNames(new NoticeEntiy(),findName,findVal);
    }
}
